from openai import OpenAI
import streamlit as st
from component import milvus_model

st.title("Chat 机器人")

model_name = st.sidebar.selectbox(
    "模型",
    ("qwen3-32b", "qwen-plus-latest"),
    index=0,
    key="model_name",
)

# 创建集合
#milvus_model.createCollection()

uploaded_file = st.sidebar.file_uploader("导入数据")
if uploaded_file:
    milvus_model.loadData(uploaded_file)

client = OpenAI(
    api_key=st.secrets["DASHSCOPE_API_KEY"],
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )

if "openai_model" not in st.session_state:
    st.session_state["openai_model"] = "gpt-3.5-turbo"

if "messages" not in st.session_state:
    st.session_state.messages = []

for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

if prompt := st.chat_input("What is up?"):
    # 查询向量数据库
    content = milvus_model.query(prompt)

    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        stream = client.chat.completions.create(
            model=model_name,
            messages=[
                {"role": m["role"], "content": m["content"]}
                for m in st.session_state.messages
            ],
            stream=True,
        )
        response = st.write_stream(stream)
    st.session_state.messages.append({"role": "assistant", "content": response})